//
//  TTMusicPlayBottomView.m
//  TTMusic
//
//  Created by yanghuiyan on 16/4/7.
//  Copyright © 2016年 cpy. All rights reserved.
//

#import "TTMusicPlayBottomView.h"
#import "TTMusicSinglePlayerViewController.h"
#import "TTMusicAVPlayer.h"
@implementation TTMusicPlayBottomView
#pragma mark - 单例的创建
+ (instancetype)playBottomView {
    static TTMusicPlayBottomView *playBottomView = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playBottomView = [[TTMusicPlayBottomView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 50, [UIScreen mainScreen].bounds.size.width, 50)];
        playBottomView.backgroundColor = COLOR(232, 233, 234);
    });
    return playBottomView;
}
#pragma mark - 重写初始化方法
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dic = [NSMutableDictionary dictionary];
        [self readNSUserDefaults];
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width / 3 * 2, self.bounds.size.height);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.playBottomCollectionView = [[TTMusicBaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width / 3 * 2, self.bounds.size.height) collectionViewLayout:layout];
        [self.playBottomCollectionView registerClass:[TTMusicPlayBottomCollectionViewCell class] forCellWithReuseIdentifier:@"TTMusicPlayBottomCollectionViewCellIdentifier"];
        self.playBottomCollectionView.pagingEnabled = YES;
        self.playBottomCollectionView.delegate = self;
        self.playBottomCollectionView.dataSource = self;
        self.playBottomCollectionView.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.playBottomCollectionView];
        self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _playButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 3 * 2 + 40, 10, self.bounds.size.height - 20, self.bounds.size.height - 20);
        [self.playButton setBackgroundImage:[[UIImage imageNamed:@"VCPlay"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_playButton];
        self.playList = [UIButton buttonWithType:UIButtonTypeSystem];
        _playList.frame = CGRectMake(_playButton.frame.origin.x + _playButton.bounds.size.width + 15, _playButton.frame.origin.y, self.bounds.size.height - 20, self.bounds.size.height - 20);
        [_playList setBackgroundImage:[UIImage imageNamed:@"VCList"] forState:UIControlStateNormal];
        [_playList addTarget:self action:@selector(creatList) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_playList];
    }
    return self;
}
#pragma mark - 出现播放列表哦
- (void)creatList {
    if ([CPYListView playListView].songsModel == _songsModel) {
    }else {
        [CPYListView playListView].songsModel = _songsModel;
    }
    [CPYListView playListView].hidden = NO;
}

- (void)setIsPlay:(BOOL)isPlay {
    _isPlay = isPlay;
    if (isPlay) {
        [self.playButton setBackgroundImage:[[UIImage imageNamed:@"VCStop"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [TTMusicAVPlayer shareTTMusicAVPlayer].isPlay = YES;
    } else {
        [self.playButton setBackgroundImage:[[UIImage imageNamed:@"VCPlay"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [TTMusicAVPlayer shareTTMusicAVPlayer].isPlay = NO;
    }
}
#pragma mark - 播放按钮的点击事件
- (void)playButtonAction:(UIButton *)sender {
//    通知播放VC更改状态
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeCondition" object:@(self.isPlay)];
    if (_isPlay) {
        [[TTMusicAVPlayer shareTTMusicAVPlayer] pause];
        [self.playButton setBackgroundImage:[[UIImage imageNamed:@"VCPlay"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [TTMusicAVPlayer shareTTMusicAVPlayer].isPlay = NO;
        _isPlay = NO;
    }else {
        [[TTMusicAVPlayer shareTTMusicAVPlayer] play];
        [self.playButton setBackgroundImage:[[UIImage imageNamed:@"VCStop"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [TTMusicAVPlayer shareTTMusicAVPlayer].isPlay = YES;
        _isPlay = YES;
    }
}
#pragma mark - 协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_songsModel) {
        return _songsModel.songs.count;
    }else {
        return 1;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_songsModel) {
        TTMusicPlayBottomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TTMusicPlayBottomCollectionViewCellIdentifier" forIndexPath:indexPath];
        cell.isCurrentPlay = self.currentLocal == indexPath.item;
        cell.backgroundColor = COLOR(242, 250, 250);
        cell.playPercent = (CGFloat)CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.currentTime) / CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.duration);
        CPYDiscoveryPageSongListModel *songListModel = [TTMusicAVPlayer shareTTMusicAVPlayer].songsModel.songs[indexPath.item];
        cell.songListModel = songListModel;
        [self SearchText];
        return cell;
    } else {
        TTMusicPlayBottomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TTMusicPlayBottomCollectionViewCellIdentifier" forIndexPath:indexPath];
        if ([_dic allKeys].count != 0) {
            cell.songLabel.text = [_dic objectForKey:@"song"];
            cell.singerLabel.text = [_dic objectForKey:@"singer"];
            [cell.personImage sd_setImageWithURL:[NSURL URLWithString:[_dic objectForKey:@"personImage"]]];
        }else {
            cell.songLabel.text = @"没有正在播放的歌曲";
            cell.personImage.backgroundColor = [UIColor grayColor];
            cell.personImage.alpha = 0.7;
        }
        return cell;
    }
}
#pragma mark - 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_songsModel) {
//        跳转到播放VC
        CPYDiscoveryPageSongListModel *songListModel = [TTMusicAVPlayer shareTTMusicAVPlayer].songsModel.songs[indexPath.item];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"singleJump" object:@{@"CPYDiscoveryPageSongListModel":songListModel, @"CPYSONGSModel":[TTMusicAVPlayer shareTTMusicAVPlayer].songsModel}];
    }else {
        [MBProgressHUD showAlertView:@"提示" andMessage:@"没有正在播放的歌曲"];

    }
}
#pragma mark - 滑动播放，下一曲，上一曲
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (_playBottomCollectionView.contentOffset.x < self.offset || _playBottomCollectionView.contentOffset.x == 0) {
        [[TTMusicSinglePlayerViewController sharePlayViewController] beforeSongButtonAction];
        self.songsModel = [TTMusicSinglePlayerViewController sharePlayViewController].songsModel;
        self.songsModel = [TTMusicAVPlayer shareTTMusicAVPlayer].songsModel;
        [_playBottomCollectionView reloadData];
    }
    else if (_playBottomCollectionView.contentOffset.x >= self.offset)
    {
        [TTMusicSinglePlayerViewController sharePlayViewController].songsModel = _songsModel;
        [[TTMusicSinglePlayerViewController sharePlayViewController] nextSongButtonAction];
        self.songsModel = [TTMusicAVPlayer shareTTMusicAVPlayer].songsModel;
        [_playBottomCollectionView reloadData];
    }
}

- (void)setSongsModel:(CPYSONGSModel *)songsModel {
    _songsModel = songsModel;
    _playBottomCollectionView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width / 3 * 2 * ([[TTMusicAVPlayer shareTTMusicAVPlayer].songsModel.songs indexOfObject:[TTMusicAVPlayer shareTTMusicAVPlayer].songDetailModel]), 0);
    self.offset = _playBottomCollectionView.contentOffset.x;
    self.isPlay = [TTMusicAVPlayer shareTTMusicAVPlayer].isPlay;
    if (_isPlay) {
        [self.playButton setBackgroundImage:[[UIImage imageNamed:@"VCStop"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [TTMusicAVPlayer shareTTMusicAVPlayer].isPlay = YES;
    } else {
        [self.playButton setBackgroundImage:[[UIImage imageNamed:@"VCPlay"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        
        [TTMusicAVPlayer shareTTMusicAVPlayer].isPlay = NO;
    }
    [_playBottomCollectionView reloadData];
}
#pragma mark - 把播放的最后一首歌存到本地
- (void)SearchText {
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSDictionary *dic = [userDefaultes dictionaryForKey:@"CPYPlayHistoryArray"];
    dic = @{@"song":[TTMusicAVPlayer shareTTMusicAVPlayer].songDetailModel.name, @"singer":[TTMusicAVPlayer shareTTMusicAVPlayer].songDetailModel.singerName, @"personImage":[TTMusicAVPlayer shareTTMusicAVPlayer].songDetailModel.picUrl};
    //将上述数据全部存储到NSUserDefaults中
    //        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaultes setObject:dic forKey:@"CPYPlayHistoryArray"];
//    [userDefaultes synchronize];// 数据永久保存
}
#pragma mark - 读取本地数据
- (void)readNSUserDefaults{
    //取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSDictionary *dic = [userDefaultes dictionaryForKey:@"CPYPlayHistoryArray"];
    self.dic = [NSMutableDictionary dictionaryWithDictionary:dic];
    [self.playBottomCollectionView reloadData];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
